﻿using System;
using System.Web;
using Birkelund.QueryStrings.Internals;

namespace Birkelund.QueryStrings.Tokens
{
    /// <summary>
    /// Class to support DateTime datatype which only renders the date and omits the time information. Can be setup to custom format.
    /// </summary>
    public class CustomDateTimeToken : ValueTypeToken<DateTime>
    {
        /// <summary>
        /// The default datetime format if no custom format is provided. This format omits the time part of the <see cref="DateTime"/> object
        /// </summary>
        public const string DEFAULT_DATETIME_RENDER_FORMAT = @"yyyy-MM-dd";
        /// <summary>
        /// Gets or sets the datetime render format.
        /// </summary>
        /// <value>The date time render format.</value>
        public string DateTimeRenderFormat { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="CustomDateTimeToken"/> class.
        /// </summary>
        /// <param name="keyName">The key.</param>
        public CustomDateTimeToken(string keyName)
            : this(keyName, DEFAULT_DATETIME_RENDER_FORMAT)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CustomDateTimeToken"/> class.
        /// </summary>
        /// <param name="keyName">The key.</param>
        /// <param name="dateTimeRenderFormat">The datetime render format.</param>
        public CustomDateTimeToken(string keyName, string dateTimeRenderFormat)
            : base(keyName)
        {
            ArgumentValidation.ThrowIfNull(dateTimeRenderFormat, "dateTimeRenderFormat");
            DateTimeRenderFormat = dateTimeRenderFormat;
        }

        /// <summary>
        /// Parses from string.
        /// </summary>
        /// <param name="stringValue">The string value.</param>
        /// <returns></returns>
        protected override DateTime OnParseFromString(string stringValue)
        {
            return Common.Cast<DateTime>(stringValue);
        }

        /// <summary>
        /// Renders the token value
        /// </summary>
        /// <returns>
        /// Returns the rendered value. Intented to be used by the framswork internal
        /// </returns>
        protected override string OnRenderTokenValue(DateTime value)
        {
            string rendered = value.ToString(DateTimeRenderFormat);
            return rendered;
        }
    }
}